package com.franklin.ideaplugin.mybatisrunner.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.intellij.psi.xml.XmlText;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author Ye Junhui
 * @since 2024/2/20
 */
public class MyStringUtils {

    /**
     * 构建El表达式
     * @param paramName
     * @return
     */
    public static String buildElExpression(String paramName){
        return String.format("#{%s}", paramName);
    }

    /**
     * 解析参数名
     * @param elExpression
     * @return
     */
    public static String resolveParamName(String elExpression){
        String paramName = "";
        int index = elExpression.indexOf(',');
        if (index > 0){
            paramName = elExpression.substring(0,index) + "}";
        }else {
            paramName = elExpression;
        }
        paramName = StrUtil.removeAll(paramName,'$','#','{','}');
        return paramName;
    }
    
    /**
     * 寻找El表达式
     * @param target
     * @return
     */
    public static List<String> findElExpressionList(String target) {
        List<String> result = Lists.newArrayList();
        for (int i = 0; i < target.length(); i++) {
            char c = target.charAt(i);
            if (c == '#' || c == '$') {
                int j = i + 1;
                boolean isEl = true;
                while (j < target.length() && target.charAt(j) != '{') {
                    if (target.charAt(j) == ' ') {
                        j++;
                    } else {
                        isEl = false;
                        break;
                    }
                }
                if (isEl) {
                    while (j < target.length() && target.charAt(j) != '}') {
                        j++;
                    }
                    result.add(StringUtils.deleteWhitespace(target.substring(i, j + 1)));
                    i = j + 1;
                }
            }
        }
        return result;
    }

}
